package com.dididoctor.patient.Activity.Inquiry;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.support.v4.util.ArrayMap;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.dididoctor.patient.MV.adapter.CommonAdapter;
import com.dididoctor.patient.MV.adapter.ViewHolder;
import com.dididoctor.patient.R;
import com.dididoctor.patient.Ui.ItemListView;
import com.dididoctor.patient.Utils.ABAppUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @version 2.0
 * @类描述：
 * @项目名称：ddgh
 * @类名称： InquiryAdapter
 * @包名称： com.dididoctor.patient.Activity.Inquiry
 * @创建人： zhanjunjie
 * @创建时间：2016/4/12 17:57
 * @修改人：
 * @修改时间：2016/4/12 17:57
 * @修改备注： new parent class(用一句话描述修改了什么)
 */
public class InquiryAdapter extends BaseAdapter {


    private static final int TYPE_COUNT = 10;//item类型的总数
    private static final int TYPE_ANSWER = 1;//问答类型
    private static final int TYPE_SINGLE = 2;//单选类型
    private static final int TYPE_MULTIPLE = 3;//多选类型

    private int currentType;//当前item类型

    //定义一个HashMap，用来存放EditText的值，Key是position
    HashMap<Integer, Answer> hashMap = new HashMap<Integer, Answer>();
    //定义一个HashMap，用来存放多选按钮的值，Key是position
    Map<Integer, Map<Integer, Object>> hashMapMultiple = new ArrayMap<Integer, Map<Integer, Object>>();
    //定义一个HashMap，用来存放单选按钮的值，Key是position
    Map<Integer, Map<Integer, Object>> hashMapSingle = new ArrayMap<Integer, Map<Integer, Object>>();

    private List<Inquiry> inquiryList = new ArrayList<>();
    private Context context;
    private Activity activity;

    public InquiryAdapter(Context context, List<Inquiry> inquiryList) {
        this.context = context;
        this.inquiryList = inquiryList;
    }

    public HashMap<Integer, Answer> getdata() {
        return hashMap;
    }

    @Override
    public int getItemViewType(int position) {
        if ("1".equals(inquiryList.get(position).getType())) {
            return TYPE_ANSWER;// 问答类型
        } else if ("3".equals(inquiryList.get(position).getType())) {
            return TYPE_MULTIPLE;// 多选类型
        } else if ("2".equals(inquiryList.get(position).getType())) {
            return TYPE_SINGLE;// 单选类型
        } else {
            return 100;
        }
    }

    @Override
    public int getViewTypeCount() {
        return TYPE_COUNT;
    }

    @Override
    public int getCount() {
        return inquiryList.size();
    }

    @Override
    public Object getItem(int position) {
        return inquiryList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    public void addData(List<Inquiry> inquiries) {
        if (this.inquiryList == null) {
            this.inquiryList = new ArrayList<Inquiry>();
        }
        this.inquiryList.addAll(inquiries);
        notifyDataSetChanged();
    }

    public void setData(List<Inquiry> datas) {
        hashMap.clear();
        hashMapMultiple.clear();
        hashMapSingle.clear();
        this.inquiryList = datas;
        notifyDataSetChanged();
    }

    @Override
    public View getView(final int position, View view, ViewGroup parent) {
        Activity activity = (Activity) context;
        View currentFocus = activity.getCurrentFocus();
        if (currentFocus != null) {
            currentFocus.clearFocus();
        }
        View answerview = null;
        View multipleview = null;
        View singleview = null;
        final MultipleAdapter multipleAdapter;
        final SingleAdapter singleAdapter;
        currentType = getItemViewType(position);
        //如果是问答
        if (currentType == TYPE_ANSWER) {
            final Inquiry inquiry = inquiryList.get(position);
            AnswerHolder answerHolder = null;
            if (answerHolder == null) {
                answerHolder = new AnswerHolder();
                answerview = LayoutInflater.from(context).inflate(R.layout.item_inquiry_one, null);
                answerHolder.mTvAnswerTitle = (TextView) answerview.findViewById(R.id.tv_answertitle);
                answerHolder.mEtAnswer = (EditText) answerview.findViewById(R.id.et_answer);
                answerview.setTag(answerHolder);
                view = answerview;
            } else {
                answerHolder = (AnswerHolder) view.getTag();
            }
            answerHolder.mTvAnswerTitle.setText("(" + (position + 1) + ")" + inquiry.getContent());
            //为editText设置TextChangedListener，每次改变的值设置到hashMap
            //我们要拿到里面的值根据position拿值
            answerHolder.mEtAnswer.addTextChangedListener(new TextWatcher() {
                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void beforeTextChanged(CharSequence s, int start,
                                              int count, int after) {

                }

                @Override
                public void afterTextChanged(Editable s) {
                    Answer answer = hashMap.get(position);
                    if (answer == null) {
                        answer = new Answer();
                    }
                    answer.setContent(s.toString());
                    answer.setQusId(inquiry.getQusId());
                    answer.setType("1");
                    //将editText中改变的值设置的HashMap中
                    hashMap.put(position, answer);
                }
            });

            //如果hashMap不为空，就设置的editText
            if (hashMap.get(position) != null) {
                answerHolder.mEtAnswer.setText(hashMap.get(position).getContent());
            }

            //如果是多选
        } else if (currentType == TYPE_MULTIPLE) {
            final Inquiry inquiry = inquiryList.get(position);
            MultipleHolder multipleHolder = null;
            //获取view
            if (multipleHolder == null) {
                multipleHolder = new MultipleHolder();
                multipleview = LayoutInflater.from(context).inflate(R.layout.item_inquiry_two, null);
                multipleHolder.mTvMultipleTitle = (TextView) multipleview.findViewById(R.id.tv_multiple);
                multipleHolder.mLvMultiple = (ItemListView) multipleview.findViewById(R.id.listview);
                multipleview.setTag(multipleHolder);
                view = multipleview;
            } else {
                multipleHolder = (MultipleHolder) view.getTag();
            }
            //Textview处理
            multipleHolder.mTvMultipleTitle.setText("(" + (position + 1) + ")" + inquiry.getContent() + "(可多选)");
            //Listview处理
            final List<InquiryItem> items = new ArrayList<>();
            final String[] stringsitem = inquiry.getOptions().split(",\\|,");
            for (int i = 0; i < stringsitem.length; i++) {
                InquiryItem inquiryItem = new InquiryItem();
                inquiryItem.setQuestion(stringsitem[i]);
                items.add(inquiryItem);
            }
            multipleAdapter = new MultipleAdapter(context, items, position);
            multipleHolder.mLvMultiple.setAdapter(multipleAdapter);
            multipleAdapter.notifyDataSetChanged();

            multipleHolder.mLvMultiple.setIsCanSelected(true);
            //ListView点击事件
            multipleHolder.mLvMultiple.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @TargetApi(Build.VERSION_CODES.KITKAT)
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int index, long id) {
                    ABAppUtil.hideSoftInput((InquiryActivity) (context));
                    CheckBox mcb = (CheckBox) view.findViewById(R.id.item_cb);
                    Map<Integer, Object> hashMapitem = new ArrayMap<Integer, Object>();
                    if (hashMapMultiple.get(position) != null) {
                        hashMapitem = hashMapMultiple.get(position);
                    }
                    InquiryItem inquiryItem = (InquiryItem) hashMapitem.get(index);
                    if (inquiryItem == null) {
                        inquiryItem = new InquiryItem();
                    }
                    inquiryItem.setQuestion(items.get(index).getQuestion());
                    if (mcb.isChecked()) {
                        inquiryItem.setIscheck(false);
                    } else {
                        inquiryItem.setIscheck(true);
                    }
                    hashMapitem.put(index, inquiryItem);
                    hashMapMultiple.put(position, hashMapitem);
                    multipleAdapter.notifyDataSetChanged();

                    Answer answer = hashMap.get(position);
                    if (answer == null) {
                        answer = new Answer();
                    }
                    List<InquiryItem> inquiryItems = new ArrayList<InquiryItem>();
                    //Map遍历得到每个item的值
                    Iterator iter = hashMapitem.keySet().iterator();
                    while (iter.hasNext()) {
                        Object key = iter.next();
                        Object val = hashMapitem.get(key);
                        inquiryItems.add((InquiryItem) val);
                    }
                    StringBuffer stringBuffer = new StringBuffer();
                    for (int i = 0; i < inquiryItems.size(); i++) {
                        stringBuffer.append(inquiryItems.get(i).getQuestion() + " ");
                    }
                    answer.setContent(stringBuffer.toString());
                    answer.setQusId(inquiry.getQusId());
                    answer.setType("3");
                    //将editText中改变的值设置的HashMap中
                    hashMap.put(position, answer);
                }
            });

            //如果是单选
        } else if (currentType == TYPE_SINGLE) {
            final Inquiry inquiry = inquiryList.get(position);
            SingleHolder singleHolder = null;
            //获取view
            if (singleHolder == null) {
                singleHolder = new SingleHolder();
                singleview = LayoutInflater.from(context).inflate(R.layout.item_inquiry_three, null);
                singleHolder.mTvSingleTitle = (TextView) singleview.findViewById(R.id.tv_singletitle);
                singleHolder.mLvSingle = (ItemListView) singleview.findViewById(R.id.listview);
                singleview.setTag(singleHolder);
                view = singleview;
            } else {
                singleHolder = (SingleHolder) view.getTag();
            }
            //Textview处理
            singleHolder.mTvSingleTitle.setText("(" + (position + 1) + ")" + inquiry.getContent() + "(单选)");
            //Listview处理
            final List<InquiryItem> items = new ArrayList<>();
            String[] stringsitem = inquiry.getOptions().split(",\\|,");
            for (int i = 0; i < stringsitem.length; i++) {
                InquiryItem inquiryItem = new InquiryItem();
                inquiryItem.setQuestion(stringsitem[i]);
                items.add(inquiryItem);
            }

            singleAdapter = new SingleAdapter(context, items, position);
            singleHolder.mLvSingle.setAdapter(singleAdapter);
            singleHolder.mLvSingle.setIsCanSelected(true);
            singleAdapter.notifyDataSetChanged();
            singleHolder.mLvSingle.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int index, long id) {
                    ABAppUtil.hideSoftInput((InquiryActivity) (context));
                    CheckBox mcb = (CheckBox) view.findViewById(R.id.item_cb);
                    TextView textview = (TextView) view.findViewById(R.id.tv_diasease);
                    //拿到一个单项的map
                    Map<Integer, Object> signmap = hashMapSingle.get(position);
                    if (signmap == null) {
                        signmap = new HashMap<Integer, Object>();
                    }
                    //将一个单项中所有的item制空
                    for (int i = 0; i < items.size(); i++) {
                        signmap.put(i, false);
                    }

                    if (mcb.isChecked()) {
                        signmap.put(index, false);
                        hashMap.remove(position);
                    } else {
                        signmap.put(index, true);
                        Answer answer = hashMap.get(position);
                        if (answer == null) {
                            answer = new Answer();
                        }
                        answer.setType("2");
                        answer.setQusId(inquiry.getQusId());
                        answer.setContent(textview.getText().toString());
                        hashMap.put(position, answer);
                    }
                    hashMapSingle.put(position, signmap);
                    singleAdapter.notifyDataSetChanged();

                }
            });
        }
        return view;
    }

    class AnswerHolder {
        TextView mTvAnswerTitle;
        EditText mEtAnswer;
    }

    class MultipleHolder {
        TextView mTvMultipleTitle;
        ItemListView mLvMultiple;
    }

    class SingleHolder {
        TextView mTvSingleTitle;
        ItemListView mLvSingle;
    }


    class MultipleAdapter extends CommonAdapter<InquiryItem> {

        private CheckBox mCb;
        private TextView mTvDiasease;
        private int position;
        private Context context;

        public MultipleAdapter(Context context, List<InquiryItem> datas, int position) {
            super(context, datas, R.layout.item_item_inquiry);
            this.position = position;
            this.context = context;
        }

        @Override
        public void convert(int index, ViewHolder helper, InquiryItem item) {
            mCb = helper.getView(R.id.item_cb);
            mTvDiasease = helper.getView(R.id.tv_diasease);
            mTvDiasease.setText(item.getQuestion());

            //如果hashMap不为空，就设置的editText
            if (hashMapMultiple != null) {
                InquiryItem inquiryItem = (InquiryItem) hashMapMultiple.get(this.position).get(index);
                if (inquiryItem != null) {
                    mCb.setChecked(inquiryItem.ischeck());
                }
            } else {
                mCb.setChecked(false);
            }
        }
    }


    class SingleAdapter extends CommonAdapter<InquiryItem> {
        private CheckBox mCb;
        private TextView mTvDiasease;
        private List<InquiryItem> datas;
        private int position;

        public SingleAdapter(Context context, List<InquiryItem> datas, int position) {
            super(context, datas, R.layout.item_item_inquiry);
            this.datas = datas;
            this.position = position;
        }

        @Override
        public void convert(final int index, ViewHolder helper, final InquiryItem item) {
            mCb = helper.getView(R.id.item_cb);
            mTvDiasease = helper.getView(R.id.tv_diasease);
            mTvDiasease.setText(item.getQuestion());
            if (hashMapSingle != null) {
                if (hashMapSingle.get(position) != null) {
                    mCb.setChecked((Boolean) hashMapSingle.get(position).get(index));
                }
            } else {
                mCb.setChecked(false);
            }
        }
    }


}
